<template>
	<view class="">
		<!--  -->
		<ben></ben>
		<!--  -->
		<view class="content">
			<!-- 商品商家列表是空的 -->

			<!-- 商品商家列表 -->
			<view class="cartShop column pad20 min30_rl rad1" style="margin-top: 30rpx;" v-for="(items, index) in list"
				:key="index">
				<!-- 商家列表 -->
				<view class="cartName-box minbottom20">
					<image :src="items.stores_logo" class="cartName-img rad1 minright10"></image>
					<view class="omit1 size26 col3 font600" style="max-width:400rpx;">
						{{ items.stores_name }}
					</view>
				</view>
				<!-- 商品列表 -->
				<view class="row" style="margin-bottom: 20rpx;" v-for="(info, k) in items.products" :key="k">

					<view class="rad1">
						<image :src="info.image" class="cartDetail-imgs rad1"></image>
					</view>
					<view class="column minleft10 flex1">
						<view class="size28 col3 font600 omit1">{{ info.title }}</view>
						<view class="size24 col9 font500 mintop10">
							规格：{{ info.specs.name }}
						</view>
						<view class="cartNum minto minbottom0">
							<view class="cartNum-txt size30 font500" style="color:#FE3C3C;">
								￥
								<text class="size36">{{ info.specs.selling_price }}</text>
							</view>
							<view class="add-sub-con">
								<u-number-box v-model="info.specs.specs_num" :disabledInput="true" :disabled="disabled"
									buttonSize="22"></u-number-box>
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>
		<view class="row font600 size30 col3" style="margin: 30rpx 50rpx 20rpx 50rpx;">
			取货信息
			<view class="minau minright0 col3 size24 font500 row align_item_c"
				@click="$jump.nav('/mypackage/user/address_list')" v-if="!order_id">
				其他取货人
				<u-icon name="arrow-right" color="#333" size="14"></u-icon>
			</view>
		</view>
		<view class="background_f rad2 pad30 min30_rl column">
			<view class="col9 size28 font500 row">
				<view style="width: 5em;">
					取货人：
				</view>
				<view class="col3">
					{{ username ? username : addlist[0].username ? addlist[0].username : '取货人' }}
				</view>
			</view>
			<view class="col9 size28 font500 mintop20 row">
				<view style="width: 5em;">
					联系电话：
				</view>
				<view class="col3">
					{{ phone ? phone : addlist[0].phone ? addlist[0].phone : '联系电话' }}
				</view>
			</view>
		</view>
		<view class="row font600 size30 col3" style="margin: 30rpx 50rpx 20rpx 50rpx;">
			优惠方式
		</view>
		<view class="background_f rad2 pad30 min30_rl column">
			<view class="col3 size28 font500 row">
				<image src="@/static/image/d.png" mode="" class="minright10" style="width: 44rpx;height: 40rpx;">
				</image>
				积分抵扣
				<view class="minau minright0 row align_item_c">
					<view class="col2F size20 font500 row" style="align-items: baseline;">
						￥
						<view class="font600 size28">
							{{ deduct_money }}
						</view>
					</view>
					<radio :checked="allSelected" :disabled="order_id ? true : false" color="#FF3F00" class="minleft10"
						style="transform:scale(0.8)" @click="selectAllAction" />
				</view>
			</view>
			<view class="col3 size24 font500 mintop10 row align_item_c" style="margin-left: 54rpx;">
				积分余额：
				<view class="size28" style="color: #FE3C3C;">
					{{ userinfo.integral }}
				</view>
				<view class="minau row align_item_c" style="margin-right: 60rpx;">
					使用积分：
					<view class="size28" style="color: #FE3C3C;">
						{{ deduct_integral }}
					</view>
				</view>
			</view>
		</view>
		<view style="height: 200rpx;">

		</view>
		<view class="background_f posfix zin2 row" style="bottom: 0;padding: 20rpx 30rpx;"
			:style="{width: screenWidth + 'px' }">
			<view class="cart-num column">
				<view class="cart-numTxt row align_item_c" v-if="order_id">
					合计：
					<view class="size22 font500" style="color: #FE3C3C;">
						￥
						<text class="font600 size30">{{ total_price }}</text>
					</view>
				</view>
				<view class="cart-numTxt row align_item_c" v-else>
					合计：
					<view class="size22 font500" style="color: #FE3C3C;">
						￥
						<text class="font600 size30">{{ total.totalPrice }}</text>
					</view>
				</view>
				<view class="size24 font500 mintop20" style="color: #4A4A4A;" v-if="order_id">
					消费可得{{ totalintegral }}积分
				</view>
				<view class="size24 font500 mintop20" style="color: #4A4A4A;" v-else>
					消费可得{{ total.totalIntegral }}积分
				</view>
			</view>
			<view class="row minau minright0">
				<view class="column" style="width: 180rpx;">
					<view class="font500 size24 col6 minbottom10" style="text-align: end;">
						共{{ total.totalNum }}件商品
					</view>
					<u-button text="确认支付" shape="circle" color="linear-gradient( 90deg, #FFCC48 0%, #FF984E 100%)"
						size="small" @click="getPayorder" v-if="order_id"></u-button>
					<u-button text="确认支付" shape="circle" color="linear-gradient( 90deg, #FFCC48 0%, #FF984E 100%)"
						size="small" @click="getAddorder" v-else></u-button>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import Decimal from 'decimal.js';
	export default {
		data() {
			return {
				type: '',
				screenWidth: '',
				user_id: '',
				address_id: '',
				order_id: '',
				username: '',
				phone: '',
				alldisabled: false,
				disabled: false,
				allSelected: 0,
				integral: '2000',
				deduct_money: '',
				deduct_integral: '',
				total_price: '',
				totalintegral: '',
				addlist: [],
				userinfo: [],
				list: [],
				order_info: [],
			}
		},

		onLoad(op) {
			this.type = uni.getStorageSync('user_type');
			if (op.order_id) {
				this.order_id = op.order_id
				this.username = op.username
				this.phone = op.phone
				this.total_price = op.total_price
				this.disabled = true
				this.totalintegral = op.totalintegral
				console.log(this.alldisabled);
			}
			this.list = JSON.parse(op.list)
			if (this.list[0].products[0].car_id) {
				this.disabled = true
			}
			console.log(this.list);
			let app = uni.getSystemInfoSync()
			this.screenWidth = app.screenWidth - 30
		},
		onShow() {
			//当前页面展示的时候他就执行该生命周期
			const token = uni.getStorageSync('token');
			this.user_id = uni.getStorageSync('user_id');
			if (token) {
				//如果存在token
				this.getAddresslist()
				this.getUserinfo()
				//按正常逻辑来讲 登录成功 我们是不是需要向服务器获取用户的信息？
				//那么我们一起来获取用户信息
			} else {

				uni.showToast({
					title: '您还未登录，正在前往登录',
					icon: 'none'
				})
				setTimeout(function() {
					uni.navigateTo({
						url: "/mypackage/user/login"
					})
				}, 1000)
			}
		},
		computed: {
			total() {
				let totalIntegral = new Decimal(0);
				let prices = new Decimal(0);
				let quantity = 0;
				if (this.list && this.list[0]) {
					this.list.forEach(item => {
						if (item.products) {
							item.products.forEach(goodItem => {
								let old_price = prices
								prices = new Decimal(goodItem.specs.selling_price).mul(Decimal(goodItem
									.specs
									.specs_num))
								prices = old_price.add(prices)
								quantity += goodItem.specs.specs_num
							})


						}
					})
					if (!this.order_id && this.deduct_money && this.userinfo) {
						if (this.userinfo.integral == 0) {
							this.deduct_money = 0
							this.deduct_integral = 0
						} else {
							if (prices.toFixed(0) > this.userinfo.integral) {
								this.deduct_money = this.userinfo.integral
								this.deduct_integral = this.userinfo.integral
							} else {
								this.deduct_money = prices.toFixed(0)
								this.deduct_integral = prices.toFixed(0)
							}
						}
						this.allSelected == 1 && (prices = new Decimal(prices).sub(Decimal(this.deduct_money)))
						if (!this.order_id) {
							this.list.forEach(item => {
								if (item.products) {
									item.products.forEach(goodItem => {
										let Integral = totalIntegral
										totalIntegral = new Decimal(goodItem.specs.sore).mul(Decimal(
											prices))
										totalIntegral = Integral.add(totalIntegral)
									})
								}
							})
						}
					}
					const a = 100
					totalIntegral = new Decimal(totalIntegral).div(new Decimal(a))
					prices < 0 ? prices = 0 : prices
				}
				return {
					totalNum: quantity,
					totalPrice: prices.toFixed(2),
					totalIntegral: totalIntegral.toFixed(0),
				}
			}
		},
		methods: {
			async getUserinfo() {
				let {
					code,
					message,
					data
				} = await this.$com.fetchGet("member/user_info/" + this.user_id)
				if (code == 200) {
					this.userinfo = data
					if (this.order_id) {
						var deduct = new Decimal(this.total.totalPrice).sub(Decimal(this.total_price))
						// if (deduct.toFixed(0) == 0) {
						// 	this.alldisabled = true
						// 	this.allSelected = 0
						// } else {
						// 	this.alldisabled = false
						// 	this.allSelected = 1
						// }
						if (deduct.toFixed(0) < 0) {
							this.deduct_money = 0
							this.deduct_integral = 0
						} else {
							this.deduct_money = deduct.toFixed(0)
							this.deduct_integral = deduct.toFixed(0)
						}

					} else {
						if (this.userinfo.integral == 0) {
							this.deduct_money = 0
							this.deduct_integral = 0
						} else {
							let totalPrice = parseFloat(this.total.totalPrice)
							totalPrice = totalPrice.toFixed(0)
							console.log(this.total.totalPrice);
							if (totalPrice > this.userinfo.integral) {
								this.deduct_money = this.userinfo.integral
								this.deduct_integral = this.userinfo.integral
							} else {
								this.deduct_money = totalPrice
								this.deduct_integral = totalPrice
							}
						}
					}

				} else {
					
					console.log();
				}
			},
			async getPayorder() { //去支付
				
				let {
					code,
					message,
					data
				} = await this.$com.fetch("order/pay_order/" + this.order_id, {
					user_id: this.user_id
				})
				if (code == 200) {
					var _this = this
					uni.requestPayment({
						provider: 'wxpay',
						timeStamp: data.timeStamp,
						nonceStr: data.nonceStr,
						package: data.package,
						signType: data.signType,
						paySign: data.paySign,
						success: function(res) {
							uni.showToast({
								title: message,
								icon: 'success'
							})
							setTimeout(function() {
								uni.navigateTo({
									url: '/indexpackage/user/pay_success'
								})
							}, 1000)
						},
						fail: function(err) {
							console.log(321);
							uni.showToast({
								icon: "error",
								title: '您取消了支付'
							})
							setTimeout(function() {
								_this.$jump.rel('/mypackage/user/order?type=' + 0)
							}, 1000)
						}
					});
			
				} else {
					
					this.$com.toast(message)
				}
			},
			async getAddorder() { //下单
				console.log(this.address_id || this.addlist.length == 0);
				if (this.address_id || this.addlist.length == 0) {
					uni.showToast({
						title: '请选择取货人信息',
						icon: 'none'
					})
					setTimeout(() => {
						uni.navigateTo({
							url: '/mypackage/user/address_list'
						})
					}, 1000)
					return
				}
				var order_info = []

				this.list.forEach((items, index) => { //js遍历数组
					items.products.forEach(item => {
						let arr = {}
						arr['car_id'] = item.car_id
						arr['product_id'] = item.id
						arr['specs_id'] = item.specs.id
						arr['specs_num'] = item.specs.specs_num
						arr['address_id'] = this.address_id ? this.address_id : this.addlist[0].id
						arr['user_id'] = this.user_id
						order_info.push(arr)
					})
				});
				console.log(order_info);
				let {
					code,
					message,
					data
				} = await this.$com.fetch("order/order_insert", {
					order_info: order_info,
					type: this.type == 3 ? 2 : 1,
					is_whether: this.allSelected == 1 ? true : false,
					total_price: this.total.totalPrice,
				})
				if (code == 200) {
					var _this = this
					if (data.length != 0) {
						uni.requestPayment({
							provider: 'wxpay',
							timeStamp: data.timeStamp,
							nonceStr: data.nonceStr,
							package: data.package,
							signType: data.signType,
							paySign: data.paySign,
							success: function(res) {
								uni.showToast({
									title: message,
									icon: 'success'
								})
								setTimeout(function() {
									uni.navigateTo({
										url: '/indexpackage/user/pay_success'
									})
								}, 1000)
							},
							fail: function(err) {
								console.log(321);
								uni.showToast({
									icon: "error",
									title: '您取消了支付'
								})
								setTimeout(function() {
									_this.$jump.rel('/mypackage/user/order?type=' + 0)
								}, 1000)
							}
						});
					} else {
						uni.showToast({
							title: message,
							icon: 'success'
						})
						setTimeout(function() {
							uni.navigateTo({
								url: '/indexpackage/user/pay_success'
							})
						}, 1000)
					}

				} else {
					this.$com.toast(message)
				}
			},
			async getAddresslist() {
				let {
					code,
					message,
					data
				} = await this.$com.fetchGet("member/user_add_list/" + this.user_id)
				if (code == 200) {
					this.addlist = data.items

				} else {
					console.log(message);
				}
			},
			prevDateFun(obj) {
				this.address_id = obj.address_id
				this.username = obj.username
				this.phone = obj.phone
				console.log(obj, 'A页面返回过来的');
			},
			selectAllAction() {
				if (this.allSelected == 0) {
					this.allSelected = 1
				} else {
					this.allSelected = 0
				}
			},
		}
	}
</script>

<style scoped lang="less">
	.content {
		.cartShop {
			box-shadow: 0 0 9rpx 3rpx #ccc;
			background-color: white;
		}

		.cartName {
			font-size: 29rpx;
			color: #333333;
			display: flex;
			align-items: center;
		}

		.cartName-box {
			height: 30rpx;
			display: flex;
			align-items: center;
		}

		.cartName-img {
			width: 50rpx;
			height: 50rpx;
		}

		.cartDetail-imgs {
			width: 200rpx;
			height: 160rpx;
		}

		.cartNum {
			display: flex;
			justify-content: space-between;
			align-items: center;
		}
	}

	.cart-num {
		font-size: 31rpx;
		color: #ffa40c;
		text-align: right;
		padding-right: 11rpx;
	}

	.cart-numTxt {
		font-size: 26rpx;
		color: #4A4A4A;
		font-weight: 600rpx;
	}
</style>